<!-- subpkg_consult/payment/payment.vue -->
<script lang="ts" setup>
  import { createOrderApi, orderPayApi, preOrderApi } from '@/apis/consult'
  import { patientDetailApi } from '@/apis/patient'
  import CustomPayment from '@/components/custom-payment/custom-payment.vue'
  import { useConsultStore } from '@/store/consult'
  import type { OrderPreData } from '@/types/consult.d.ts'
  import type { PatientItem } from '@/types/patientItem'
  import { ref } from 'vue'

  // 1. 生成预支付订单
  // 患者相关的数据（不具有响应性）
  const store = useConsultStore()
  // 预付订单信息
  const preOrderInfo = ref({} as OrderPreData)
  /** 订单id */
  const orderId = ref('')
  // 生成预付订单
  const createPreOrder = async () => {
    // 预付订单信息
    const data = await preOrderApi({ type: store.type, illnessType: store.illnessType })
    // 渲染订单数据
    preOrderInfo.value = data
  }
  /** 患者信息 */
  createPreOrder()
  const patientDetail = ref({} as PatientItem)
  const getPatientDetail = async () => {
    const res = await patientDetailApi(store.patientId)
    patientDetail.value = res as PatientItem
  }
  getPatientDetail()
  const paymentRef = ref()

  const onPaymentButtonClick = async () => {
    if (orderId.value !== '')
      return uni.showToast({
        title: '订单不能重复创建！',
      })

    // 生成订单接口
    const data = await createOrderApi({
      type: store.type,
      illnessType: store.illnessType,
      patientId: store.patientId,
      depId: store.depId,
      illnessDesc: store.illnessInfo.illnessDesc,
      illnessTime: store.illnessInfo.illnessTime,
      consultFlag: store.illnessInfo.consultFlag,
      pictures: store.illnessInfo.pictures,
    })

    // 接收订单ID
    orderId.value = data.id
    // 将 Pinia 中缓存的数据清空掉（订单已创建完成）
    store.clear()
    paymentRef.value.open()
    // 选择支付渠道...
  }
  // 4. 当支付弹层关闭时
  const onPaymentClose = async () => {
    const { confirm } = await uni.showModal({
      title: '关闭支付',
      content: '取消支付将无法获得医生回复，医生接诊名额有限，是否确认关闭？',
      cancelText: '仍要关闭',
      cancelColor: '#848484',
      confirmText: '继续支付',
      confirmColor: '#16C2A3',
    })

    if (!confirm) {
      paymentRef.value.close()
      uni.reLaunch({
        url: '/pages/index/index',
      })
    }
  }

  const onPaymentConfirm = async (index: number) => {
    if (index === 0)
      return uni.showToast({
        title: '暂不支持微信支付!',
      })

    // 调用后端提供的支付接口
    const { payUrl } = await orderPayApi({
      orderId: orderId.value,
      paymentMethod: index + '',
      payCallback: 'http://localhost:5173/#/subpkg_consult/room/room',
    })

    // #ifdef H5
    // 引导用户支付（地址跳转方式）
    window.location.href = payUrl
    // #endif

    // #ifdef MP-WEIXIN
    // 引导用户支付（wx.requestPayment 小程序直接拉起支付）
    // wx.requestPayment({
    //   // 4 个参数
    // })
    // #endif
  }
</script>

<template>
  <scroll-page>
    <view class="payment-page">
      <uni-section
        title-font-size="32rpx"
        title-color="#121826"
        padding="30rpx"
        :title="`图文问诊 ${preOrderInfo.payment}元`"
      >
        <uni-list :border="false">
          <uni-list-item
            title="极速问诊"
            note="自动分配医生"
            thumb="/static/uploads/doctor-avatar.jpg"
            thumb-size="lg"
          />
          <uni-list-item
            title="优惠券"
            show-arrow
            :right-text="`-¥${preOrderInfo.couponDeduction}`"
          />
          <uni-list-item title="积分抵扣">
            <template #footer>
              <view class="uni-list-text-red"> -¥{{ preOrderInfo.pointDeduction }} </view>
            </template>
          </uni-list-item>
          <uni-list-item title="实付款">
            <template #footer>
              <view class="uni-list-text-red"> ¥{{ preOrderInfo.actualPayment }} </view>
            </template>
          </uni-list-item>
        </uni-list>
      </uni-section>

      <uni-section title-font-size="32rpx" title-color="#121826" padding="30rpx" title="患者资料">
        <uni-list :border="false">
          <uni-list-item title="患者信息">
            <template #footer>
              <view class="uni-list-text-gray">
                {{ patientDetail.name }} | {{ patientDetail.genderValue }} |
                {{ patientDetail.age }}岁
              </view>
            </template>
          </uni-list-item>
          <uni-list-item border title="病情描述" :note="store.illnessInfo.illnessDesc" />
        </uni-list>
      </uni-section>
    </view>
    <!-- 下一步操作 -->
    <view class="next-step">
      <view class="total-amount">
        合计: <text class="number">¥{{ preOrderInfo.actualPayment }}</text>
      </view>
      <CustomPayment
        @confirm="onPaymentConfirm"
        @close="onPaymentClose"
        :orderId="orderId"
        :amount="preOrderInfo.actualPayment"
        ref="paymentRef"
      />
      <button class="uni-button" @click="onPaymentButtonClick">立即支付</button>
    </view>
  </scroll-page>
</template>
<style lang="scss">
  @import './index.scss';
</style>
